package dbutils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by kevin on 2020/3/29.
 */
public class JdbcUtils {
    //加载配置文件的默认配置,需要配置c3p0-config.xml(放在src/main/Resource目录下即可)
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

    //事务专用连接
    private static Connection connection = null;

    public static Connection getConnection() throws SQLException{
        if(connection!=null){
            return connection;
        }else{
            return dataSource.getConnection();
        }
    }

    public static DataSource getDataSource(){
        return dataSource;
    }

    /**
     * 开启事务
     * 1.获取一个Connection,设置它的setAutoCommit(false)
     * 2.还要保证dao中使用的连接是我们刚刚创建的
     */
    public static void beginTransaction(){
        try {
            if(connection!=null){
                throw new SQLException("已经开启事务,请勿重复操作");
            }
            connection = getConnection();
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     * 1.获取beginTransaction提供的Connection,然后调用commit方法
     */
    public static void commitTransaction(){

        try {
            if(connection==null){
                throw new SQLException("还没有开启事务!不能提交");
            }
            connection.commit();
            connection.close();
            connection= null;//必须清空值否则下次会得到一个已经关闭的连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     * 1.获取beginTransaction提供的Connection,然后调用了rollback方法
     */
    public static void rollbackTransaction(){
        try {
            if(connection==null){
                throw new SQLException("还没有开启事务!不能回滚");
            }
            connection.rollback();
            connection.close();
            connection= null;//必须清空值否则下次会得到一个已经关闭的连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
